#include "yk_baseitem.h"
#include "ui_yk_baseitem.h"

#include "pub_var.h"
#include <QSettings>
#include <QMessageBox>
#include <QJsonDocument>
#include <QNetworkReply>
#include <QCompleter>
#include <QSqlError>

Yk_baseitem::Yk_baseitem(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Yk_baseitem)
{
    ui->setupUi(this);

    //恢复当前窗口位置
    QSettings setIni("clin.ini", QSettings::IniFormat);
    QRect rct = setIni.value("windowState/yk_baseitem").toRect();
    this->setGeometry(rct);

    //数据库连接
    qrm = new QSqlQuery(pub::db_m);
    qro = new QSqlQuery(pub::db_o);
    qrot = new QSqlQuery(pub::db_o);

    md_itm = new QSqlQueryModel(this);
    md_cpny = new QSqlQueryModel(this);

    //项目维护相关

    sq = "select FAC_NAME, FAC_CODE from PHA_COM_COMPANY where COMPANY_TYPE = '0' and VALID_FLAG = '1' order by FAC_NAME";
    qDebug()<<"提取生产厂家："<<sq;

    QStringList itemList;
    qro->exec(sq);
    while(qro->next())
    {
        itemList << qro->value(0).toString();
        producer_code.append(qro->value(0).toString() + "^" + qro->value(1).toString() + "^");
    }

    QCompleter *comp = new QCompleter(itemList,ui->cbb_producer_code->model());// 自动补全实例的构建
    comp->setFilterMode(Qt::MatchContains);    // 设置匹配模式，只要包含就显示
    comp->setCaseSensitivity(Qt::CaseInsensitive);    // 设置大小写区分，不区大小写
    comp->setCompletionMode(QCompleter::PopupCompletion);    // 设置向用户提供补全的方式
    ui->cbb_producer_code->setCompleter(comp);    // 装载补全实例


    //producer_code = pub::fillCombo(ui->cbb_producer_code, sq, -1, qrot);

    sq = "select dept_name, dept_code from com_department where valid_state = '1' and regdept_flag = '1'";
    qDebug()<<"提取门诊科室："<<sq;
    drug_consume_depts = pub::fillCombo(ui->cbb_dept_code, sq, -1, qrot);
    ui->cbb_dept_code->addItem("通用");

    sq = "select name from com_dict_com where dic_type='剂量单位' and valid_flag = '1' ";    //
    qDebug()<<"提取药品剂量单位："<<sq;
    dose_units = pub::fillCombo(ui->cbb_dose_unit, sq , -1);//

    sq = "select name from com_dict_com where dic_type='使用单位' and valid_flag = '1' ";    //最小单位
    qDebug()<<"提取药品最小单位："<<sq;
    min_units = pub::fillCombo(ui->cbb_min_unit, sq , -1);//

    sq = "select name from com_dict_com where dic_type='包装单位' and valid_flag = '1' ";
    qDebug()<<"提取药品包装单位："<<sq;
    pack_units = pub::fillCombo(ui->cbb_pack_unit, sq , -1);//

    sq = "SELECT name,HIS_CLASS_CODE FROM ORDT_TERM_CLASS where ISDRUG = '1'";
    qDebug()<<"提取系统类别："<<sq;
    sys_class = pub::fillCombo(ui->cbb_class_code, sq , -1, qrot);//

    sq = "SELECT NAME, code FROM com_dictionary WHERE TYPE = 'DRUGQUALITY' AND VALID_STATE = '1' ORDER BY sort_id";
    qDebug()<<"提取药品属性："<<sq;
    drug_quality = pub::fillCombo(ui->cbb_drug_quality, sq , -1, qrot);//

    sq = " select name, code from com_dictionary where type ='ITEMTYPE' and  VALID_STATE  = '1' order by sort_id ";
    qDebug()<<"提取药品类别："<<sq;
    drug_type = pub::fillCombo(ui->cbb_drug_type, sq , -1, qrot);//

    sq = "select name,code from com_dictionary where  type ='DRUGGRADE' and  VALID_STATE  = '1' order by sort_id";
    qDebug()<<"提取药品等级："<<sq;
    item_grade = pub::fillCombo(ui->cbb_item_grade, sq , -1, qrot);//

    sq = "select name,code from com_dictionary where  type ='MINFEE' and code in('001', '002', '003')";
    qDebug()<<"提取费用类别："<<sq;
    fee_code = pub::fillCombo(ui->cbb_fee_code, sq , -1, qrot);//

    sq = "select name,code from com_dictionary where  type ='DOSAGEFORM' and valid_state = '1' order by sort_id";
    qDebug()<<"提取药品剂型："<<sq;
    dose_models = pub::fillCombo(ui->cbb_dose_model_code, sq , -1, qrot);//

    sq = "select name, code from com_dict_com where dic_type = '技术职称' and valid_flag = '1' order by ord";
    qDebug()<<"提取医师职级："<<sq;
    duty_constrains = pub::fillCombo(ui->cbb_duty_constrain, sq , -1);//

    ui->tabWidget->setCurrentIndex(0);  //药品项目维护

    is_new_fac = false;

    initialFinished = true;

}

Yk_baseitem::~Yk_baseitem()
{
    delete ui;
}

void Yk_baseitem::closeEvent(QCloseEvent *event)
{
    Q_UNUSED(event);
    QSettings setIni("clin.ini", QSettings::IniFormat);
    setIni.setValue("windowState/yk_baseitem", QVariant(this->geometry()));

    emit destroyW( "yk_baseitem" );

}

void Yk_baseitem::on_pbExit_clicked()
{
    close();
}

void Yk_baseitem::on_pb_search_itm_clicked()
{

    if(!ui->ckb_no_zero->isChecked() && !ui->ckb_zero->isChecked())
    {
        QMessageBox::information(this, "注意", "库存 0 和 库存非 0 至少应该选择一项！");
        return;
    }

    QString key = ui->leKey->text().trimmed();
    sq = " select distinct pha.TRADE_NAME 药品名称, pha.SPECS 规格, f_c.fac_name 厂家, "
         " pha.drug_code "
         " from pha_com_baseinfo pha ";
    sq += " LEFT JOIN PHA_COM_COMPANY f_c ON f_c.FAC_CODE = pha.PRODUCER_CODE ";
    sq += " LEFT JOIN PHA_COM_STOCKINFO STO ON sto.drug_code = pha.DRUG_CODE ";
    sq += " where (pha.SPELL_CODE like '%" + key.toUpper() + "%' or TRADE_NAME like '%" + key + "%') ";

    if(ui->ckb_in_use->isChecked())
    {
        sq += " and pha.valid_state = '1' ";
    }

    if(ui->ckb_no_zero->isChecked() && ui->ckb_zero->isChecked())
    {
        // 0 和 非0 同时选择，不需要对库存进行判断
    }
    else if(ui->ckb_no_zero->isChecked())
    {
        sq += " and sto.store_sum <> 0 ";
    }
    else if(ui->ckb_zero->isChecked())
    {
        sq += " and sto.store_sum = 0 ";
    }

    sq += " order by pha.TRADE_NAME";

    qDebug()<<"药品目录检索："<<sq;
    md_itm->setQuery(sq, pub::db_o);

    ui->tv_config->setModel(md_itm);
    int width = ui->tv_config->width();
    pub::setColumnWidth(ui->tv_config, "0.3^0.2^0.4", width, 25);//^0^0^0^0^0^0^0^0^0^0^0^0^0^0^0^0^0^0^0^0^0


}

void Yk_baseitem::on_leKey_returnPressed()
{
    on_pb_search_itm_clicked();
}

void Yk_baseitem::on_tv_config_doubleClicked(const QModelIndex &index)
{
    on_tv_config_clicked(index);
}

void Yk_baseitem::on_tv_config_clicked(const QModelIndex &index)
{
    is_new_drug = false;
    ui->le_retail_price->setEnabled(false);
    ui->le_purchase_price->setEnabled(false);

    item_detail.clear();
    item_detail.insert("item_name", index.siblingAtColumn(0).data().toString());   //品名
    item_detail.insert("specs", index.siblingAtColumn(1).data().toString());   //规格
    item_detail.insert("fac_name", index.siblingAtColumn(2).data().toString());   //生产商
    item_detail.insert("approve_info", index.siblingAtColumn(3).data().toString());   //批准文号, 项目维护的 drug_code


    // [approve_info] 实际保存内容为 [drug_code]
    sq = "select * from pha_com_baseinfo where drug_code = '" + item_detail["approve_info"] + "'";
    qro->exec(sq);
    qDebug()<<"select all fields : "<< sq;
    qro->next();

    ui->le_drug_code->setText(qro->value("drug_code").toString());// '药品编码';
    ui->le_trade_name->setText(qro->value("trade_name").toString());// '商品名称';
    ui->le_spell_code->setText(qro->value("spell_code").toString());// '商品名拼音码';
    ui->le_specs->setText(qro->value("specs").toString());// '规格';
    ui->le_retail_price->setText(QString::number(qro->value("retail_price").toDouble(), 'f', 2));// '参考零售价';
    ui->le_purchase_price->setText(QString::number(qro->value("purchase_price").toDouble(), 'f', 2));// '最新购入价';
    ui->le_pack_qty->setText(qro->value("pack_qty").toString());// '包装数';
    ui->le_base_dose->setText(qro->value("base_dose").toString());// '基本剂量';
    ui->le_approve_info->setText(qro->value("approve_info").toString());// '批文信息';
    ui->le_package_num->setText(qro->value("package_num").toString());// '整件包装数量';
    ui->le_id_code->setText(qro->value("id_code").toString());// '标志码';
    ui->le_id_code_count->setText(qro->value("id_code_count").toString());// '码容量';
    QString tmp;

    tmp = qro->value("pack_unit").toString();// '包装单位';
    if(ui->cbb_pack_unit->findText( tmp, Qt::MatchExactly) < 0)
    {
        ui->cbb_pack_unit->setCurrentIndex(-1);
    }
    else
    {
        ui->cbb_pack_unit->setCurrentText(tmp);
    }

    tmp = qro->value("class_code").toString();
    qrot->exec("SELECT name FROM ORDT_TERM_CLASS where ISDRUG = '1' and HIS_CLASS_CODE = '" + tmp + "'");
    qrot->next();
    ui->cbb_class_code->setCurrentText(qrot->value(0).toString());//  '系统类别';

    tmp = qro->value("fee_code").toString();
    ui->cbb_fee_code->setCurrentText(pub::getDicN_o("MINFEE", tmp, qrot));//  '最小费用代码';

    tmp = qro->value("drug_type").toString();
    ui->cbb_drug_type->setCurrentText(pub::getDicN_o("ITEMTYPE", tmp, qrot));//  '药品类别';

    tmp = qro->value("drug_quality").toString();
    ui->cbb_drug_quality->setCurrentText(pub::getDicN_o("DRUGQUALITY", tmp, qrot));//  '药品性质';

    tmp = qro->value("min_unit").toString();// '最小单位';
    if(ui->cbb_min_unit->findText( tmp, Qt::MatchExactly) < 0)
    {
        ui->cbb_min_unit->setCurrentIndex(-1);
    }
    else
    {
        ui->cbb_min_unit->setCurrentText(tmp);
    }

    tmp = qro->value("dose_unit").toString();//  '剂量单位';
    if(ui->cbb_dose_unit->findText( tmp, Qt::MatchExactly) < 0)
    {
        ui->cbb_dose_unit->setCurrentIndex(-1);
    }
    else
    {
        ui->cbb_dose_unit->setCurrentText(tmp);
    }

    tmp = qro->value("dose_model_code").toString();//  '剂型编码';
    tmp = pub::getDicN_o("DOSAGEFORM", tmp, qrot);
    if(tmp == "")
    {
        ui->cbb_dose_model_code->setCurrentIndex(-1);//
    }
    else
    {
        ui->cbb_dose_model_code->setCurrentText(tmp);//
    }

    ui->cbb_phy_function1->setCurrentText("");//  '一级药理作用';
    ui->cbb_phy_function2->setCurrentText("");//  '二级药理作用';
    ui->cbb_phy_function3->setCurrentText("");//  '三级药理作用';

    ui->cbb_producer_code->setCurrentText(item_detail["fac_name"]); //  '生产厂家';

    tmp = qro->value("dept_code").toString();
    if(tmp == "0")
    {
        tmp = "通用";
    }
    else
    {
        qrot->exec("select dept_name from com_department where "
                   " valid_state = '1' and dept_code = '" + tmp + "'");
        qrot->next();
        tmp = qrot->value(0).toString();
    }
    if(tmp == "")
    {
        ui->cbb_dept_code->setCurrentIndex(-1);//  '统计关联科室，药品主要使用科室';
    }
    else
    {
        ui->cbb_dept_code->setCurrentText(tmp);//  '统计关联科室，药品主要使用科室';
    }

    tmp = qro->value("item_grade").toString();
    ui->cbb_item_grade->setCurrentText(pub::getDicN_o("DRUGGRADE", tmp, qrot));//  药品等级

    tmp = qro->value("duty_constrain").toString(); //  药品使用职级限制
    if(tmp.isEmpty())
    {
        ui->cbb_duty_constrain->setCurrentIndex(-1);;
    }
    else
    {
        ui->cbb_duty_constrain->setCurrentText(pub::getDicN("技术职称", tmp));
    }
    ui->pt_manual->setPlainText(qro->value("manual").toString());// '说明书内容';

    bool val = (qro->value("valid_state").toString() == "0") ? true : false;
    ui->ckb_valid_state->setChecked(val);// '有效性标志 1 在用 0 停用 ;

    val = (qro->value("self_flag").toString() == "1") ? true : false;
    ui->ckb_self_flag->setChecked(val);//  '自制标志 0-非自产，1-自产';

    val = (qro->value("test_flag").toString() == "1") ? true : false;
    ui->ckb_test_flag->setChecked(val);//  '是否需要试敏 0不需要1需要';

    val = (qro->value("show_flag").toString() == "1") ? true : false;
    ui->ckb_show_flag->setChecked(val);//  '大屏幕显示标记 0非屏幕显示  1为大屏幕显示';

    val = (qro->value("is_inject").toString() == "1") ? true : false;
    ui->ckb_is_inject->setChecked(val);//  '注射剂';

    val = (qro->value("is_antibacterial").toString() == "1") ? true : false;
    ui->ckb_is_antibacterial->setChecked(val);//  '抗菌药';

    val = (qro->value("is_03").toString() == "1") ? true : false;
    ui->ckb_is_03->setChecked(val);//  '基药标志';

    val = (qro->value("is_9906").toString() == "1") ? true : false;
    ui->ckb_is_9906->setChecked(val);//  '集采药品标志';

    val = (qro->value("split_type").toString() == "0") ? true : false;
    ui->ckb_split_type->setChecked(val);//  '拆零标志';
}

void Yk_baseitem::on_pb_new_drug_clicked()
{
    sq = "SELECT SEQ_PHA_COM_BASEINFO_DRUG_CODE.NEXTVAL FROM DUAL";
    qDebug()<<"生成药品编码："<<sq;
    qro->exec(sq);
    qro->next();
    QString base_code = "Y00000000000";
    QString new_code = qro->value(0).toString();
    QString new_drug_code = base_code.replace(base_code.length() - new_code.length(), new_code.length(), new_code);

    item_info_clear();
    ui->le_drug_code->setText(new_drug_code);
    is_new_drug = true;
    ui->le_retail_price->setEnabled(true);
    ui->le_purchase_price->setEnabled(true);
}

void Yk_baseitem::item_info_clear()
{
    ui->le_drug_code->clear();// '药品编码';
    ui->le_trade_name->clear();// '商品名称';
    ui->le_spell_code->clear();// '商品名拼音码';
    ui->le_specs->clear();// '规格';
    ui->le_retail_price->clear();// '参考零售价';
    ui->le_purchase_price->clear();// '最新购入价';
    ui->le_pack_qty->clear();// '包装数';
    ui->le_base_dose->clear();// '基本剂量';
    ui->le_approve_info->clear();// '批文信息';
    ui->le_package_num->clear();// '整件包装数量';
    ui->le_id_code->clear();    //药品识别码
    ui->le_id_code_count->clear();    //药品识别码容量
    ui->cbb_pack_unit->setCurrentIndex(-1);// '包装单位';
    ui->cbb_class_code->setCurrentIndex(-1);//  '系统类别';
    ui->cbb_fee_code->setCurrentIndex(-1);//  '最小费用代码';
    ui->cbb_drug_type->setCurrentIndex(-1);//  '药品类别';
    ui->cbb_drug_quality->setCurrentIndex(-1);//  '药品性质';
    ui->cbb_min_unit->setCurrentIndex(-1);//  '最小单位';
    ui->cbb_dose_model_code->setCurrentIndex(-1);//  '剂型编码';
    ui->cbb_dose_unit->setCurrentIndex(-1);//  '剂量单位';
    ui->cbb_phy_function1->setCurrentIndex(-1);//  '一级药理作用';
    ui->cbb_phy_function2->setCurrentIndex(-1);//  '二级药理作用';
    ui->cbb_phy_function3->setCurrentIndex(-1);//  '三级药理作用';
    ui->cbb_producer_code->setCurrentIndex(-1);//  '生产厂家';
    ui->cbb_dept_code->setCurrentIndex(-1);//  '统计关联科室，药品主要使用科室';
    ui->cbb_item_grade->setCurrentIndex(-1);//  药品等级
    ui->cbb_duty_constrain->setCurrentIndex(-1);//  药品使用职级限制
    ui->pt_manual->clear();// '说明书内容';
    ui->ckb_valid_state->setChecked(false);// '有效性标志 1 在用 0 停用 2 废弃';
    ui->ckb_self_flag->setChecked(false);//  '自制标志 0-非自产，1-自产';
    ui->ckb_test_flag->setChecked(false);//  '是否需要试敏 0不需要1需要';
    ui->ckb_show_flag->setChecked(false);//  '大屏幕显示标记 0非屏幕显示  1为大屏幕显示';
    ui->ckb_is_inject->setChecked(false);//  '注射剂';
    ui->ckb_is_antibacterial->setChecked(false);//  '抗菌药';
    ui->ckb_is_03->setChecked(false);//  '基药标志';
    ui->ckb_is_9906->setChecked(false);//  '集采药品标志';
    ui->ckb_split_type->setChecked(false);//拆零使用

    //sq = "select FAC_NAME, FAC_CODE from PHA_COM_COMPANY where COMPANY_TYPE = '0' and VALID_FLAG = '1' order by FAC_NAME";
    //qDebug()<<"提取生产厂家："<<sq;
    //producer_code = pub::fillCombo(ui->cbb_producer_code, sq, -1, qrot);

}
void Yk_baseitem::on_pb_save_itm_clicked()
{
    if(!ui->ckb_valid_state->isChecked() )
    {
        //启用的项目，进行有效性校验
        if(!item_check())
        {
            return;
        }
    }
    else
    {
        //停用项目，不进行有效性校验, 只检查库存数量
//        int pos = pub::searchStr(store_depts, "^", ui->cbbStoreDept->currentText()) + 1;
//        QString dept = pub::getStr(store_depts, "^", pos);//库存单位

        sq = "select sum(store_sum) from pha_com_stockinfo "
             " where drug_code = '%1'";
             //" and storage_code = '%2'";
        sq = sq.arg(ui->le_drug_code->text());
                //.arg(dept);


        qDebug()<<"检查库存："<<sq;
        qro->exec(sq);
        qro->next();
        int sum = qro->value(0).toInt();

        if(sum > 0)
        {
            QString msg = "指定品种库存大于 0 ，确认要停用？";
            QMessageBox::StandardButton bt;
            bt = QMessageBox::question(this, "注意", msg);

            if(bt != QMessageBox::Yes)
            {
                return;
            }
        }

        sq = " update pha_com_baseinfo set valid_state = '0'";
        sq += " where drug_code = '" + ui->le_drug_code->text() + "'";
        qro->exec(sq);
        qDebug()<<"药品停用："<<sq;
        QMessageBox::information(this, "注意", "药品已经停用！");
        return;
    }


    int pos = 0;    //检索

    if(is_new_drug)
    {
        //检查是否存在同厂家同文号品种

        sq = "select trade_name from pha_com_baseinfo where ";

        pos = pub::searchStr(producer_code, "^", ui->cbb_producer_code->currentText());
        sq += " producer_code = '" + pub::getStr(producer_code, "^", pos + 1) + "'";//  producer_code '生产厂家';
        sq += " and approve_info = '" + ui->le_approve_info->text().trimmed() + "'";//批准文号
        qDebug()<<"检查药品重复："<<sq;
        qro->exec(sq);
        if(qro->next())
        {
            QMessageBox::StandardButton bt;
            bt = QMessageBox::information(this, "注意", "新录入品种已经有相同厂家和批准文号的记录，确定要增加？",
                                          QMessageBox::Yes | QMessageBox::No);
            if(bt != QMessageBox::Yes)
            {
                return;
            }
        }

        //插入新品种
        sq = "insert into pha_com_baseinfo ";
        sq += "( drug_code, trade_name, spell_code, regular_name, regular_spell, class_code,";
        sq += " fee_code, drug_type, drug_quality, specs, retail_price, purchase_price,";
        sq += " pack_unit, pack_qty, min_unit, dose_model_code, base_dose, dose_unit, usage_code,";
        sq += " frequency_code, once_dose, caution, phy_function1, phy_function2, phy_function3,";
        sq += " valid_state, self_flag, test_flag, show_flag, producer_code, approve_info, ";
        sq += " store_condition, brief_introduction, manual, bar_code, oper_code, oper_date,";
        sq += " create_time, is_inject, is_antibacterial, "
              " is_03, is_9906, split_type, package_num, "
              " dept_code, duty_constrain, item_grade, id_code, id_code_count ";
        sq += ") values (";
        sq += "'" + ui->le_drug_code->text() + "',";// drug_code'药品编码';
        sq += "'" + ui->le_trade_name->text().trimmed() + "',";//  trade_name'商品名称';
        sq += "'" + ui->le_spell_code->text().trimmed() + "',";//  spell_code'商品名拼音码';
        sq += "'',"; // regular_name '通用名';
        sq += "'',"; //regular_spell'通用名拼音码';

        pos = pub::searchStr(sys_class, "^", ui->cbb_class_code->currentText());
        sq += "'" + pub::getStr(sys_class, "^", pos + 1) + "',";// class_code '系统类别';

        pos = pub::searchStr(fee_code, "^", ui->cbb_fee_code->currentText());
        sq += "'" + pub::getStr(fee_code, "^", pos + 1) + "',";//  fee_code '最小费用代码';

        pos = pub::searchStr(drug_type, "^", ui->cbb_drug_type->currentText());
        sq += "'" + pub::getStr(drug_type, "^", pos + 1) + "',";//  drug_type '药品类别';

        pos = pub::searchStr(drug_quality, "^", ui->cbb_drug_quality->currentText());
        sq += "'" + pub::getStr(drug_quality, "^", pos + 1) + "',";//  drug_quality '药品性质';

        sq += "'" + ui->le_specs->text().trimmed() + "',";// specs '规格';
        sq += ui->le_retail_price->text() + ",";// retail_price '参考零售价';
        sq += ui->le_purchase_price->text() + ",";// purchase_price '最新购入价';
        sq += "'" + ui->cbb_pack_unit->currentText() + "',"; //pack_unit'包装单位';
        sq += ui->le_pack_qty->text() + ",";// pack_qty '包装数';
        sq += "'" + ui->cbb_min_unit->currentText() + "',"; // min_unit'最小单位';

        QString dose_model = ui->cbb_dose_model_code->currentText();
        if(dose_model.isEmpty())
        {
            sq += "'',";//  dose_model_code '剂型编码';
        }
        else
        {
            pos = pub::searchStr(dose_models, "^", dose_model);
            sq += "'" + pub::getStr(dose_models, "^", pos + 1) + "',";//  dose_model_code '剂型编码';
        }

        sq += ui->le_base_dose->text() + ",";// base_dose '基本剂量';
        sq += "'" + ui->cbb_dose_unit->currentText() + "',"; // dose_unit'剂量单位';
        sq += "'',"; // '用法编码';
        sq += "'',"; // '频次编码';
        sq += "'',"; // '一次用量';
        sq += "'',"; // '注意事项';
        sq += "'',";// + phy_function1 '一级药理作用';
        sq += "'',";// + phy_function2 '二级药理作用';
        sq += "'',";// + phy_function3 '三级药理作用';

        if(ui->ckb_valid_state->isChecked())// + valid_state '有效性标志 1 在用 0 停用 2 废弃';
        {
            sq += "'0',";
        }else{
            sq += "'1',";//
        }

        if(ui->ckb_self_flag->isChecked())// + self_flag '自制标志 0-非自产，1-自产';
        {
            sq += "'1',";
        }else{
            sq += "'0',";//
        }

        if(ui->ckb_test_flag->isChecked())// + test_flag '是否需要试敏 0不需要1需要';
        {
            sq += "'1',";
        }else{
            sq += "'0',";//
        }

        if(ui->ckb_show_flag->isChecked())// + show_flag '大屏幕显示标记 0非屏幕显示  1为大屏幕显示'
        {
            sq += "'1',";;
        }else{
            sq += "'0',";//
        }

        pos = pub::searchStr(producer_code, "^", ui->cbb_producer_code->currentText());
        sq += "'" + pub::getStr(producer_code, "^", pos + 1) + "',";//  producer_code '生产厂家';

        sq += "'" + ui->le_approve_info->text().trimmed() + "',";// approve_info '批文信息';
        sq += "'',";// + store_condition '储藏条件';
        sq += "'',";// + brief_introduction '药品简介';
        sq += "'" + ui->pt_manual->toPlainText() + "',";// + manual '说明书内容';
        sq += "'',";// + bar_code '条形码';
        sq += "'" + pub::usr_code + "',";// oper_code '操作员';
        sq += "sysdate,";// + oper_date '操作时间';
        sq += "sysdate,";// + create_time '字典建立时间';

        if(ui->ckb_is_inject->isChecked())// is_inject '注射剂';
        {
            sq += "'1',";
        }else{
            sq += "'0',";
        }

        if(ui->ckb_is_antibacterial->isChecked())   //is_antibacterial '抗菌药';
        {
            sq += "'1',";
        }else{
            sq += "'0',";
        }

        if(ui->ckb_is_03->isChecked())  //is_03 '基药标志';
        {
            sq += "'1',";
        }else{
            sq += "'0',";
        }

        if(ui->ckb_is_9906->isChecked())  //is_9906 '集采药品标志';
        {
            sq += "'1',";
        }else{
            sq += "'0',";
        }

        if(ui->ckb_split_type->isChecked())  //拆分标志
        {
            sq += "'0',";
        }else{
            sq += "'1',";
        }

        sq += ui->le_package_num->text() + ",";// '整件包装数量';

        pos = pub::searchStr(drug_consume_depts, "^", ui->cbb_dept_code->currentText());
        QString tmp_dept ;
        if(pos == 0)
        {
            tmp_dept = "0";
        }
        else
        {
            tmp_dept = pub::getStr(drug_consume_depts, "^", pos + 1);
        }
        sq += "'" + tmp_dept + "',";//dept_code '统计关联科室，药品主要使用科室';

        pos = pub::searchStr(duty_constrains, "^", ui->cbb_duty_constrain->currentText());
        sq += "'" + pub::getStr(duty_constrains, "^", pos + 1) + "', ";// duty_constrain '职级限定';

        pos = pub::searchStr(item_grade, "^", ui->cbb_item_grade->currentText());
        sq += "'" + pub::getStr(item_grade, "^", pos + 1) + "', ";// 药品等级

        QString id_code = ui->le_id_code->text().trimmed();

        if(id_code.length() == 20)
        {
            id_code = id_code.mid(0, 7);
        }

        sq += "'" + id_code + "',";// 药品 id 编码;
        sq += ui->le_id_code_count->text() ;// id 编码容量;

        sq += ")";
        qDebug()<<"插入新的药品基础数据："<<sq;
    }
    else
    {
        //更新旧数据

        sq = " update pha_com_baseinfo set ";
        sq += " trade_name = '" + ui->le_trade_name->text().trimmed() + "',";//  trade_name'商品名称';
        sq += " spell_code = '" + ui->le_spell_code->text().trimmed() + "',";//  spell_code'商品名拼音码';

        pos = pub::searchStr(sys_class, "^", ui->cbb_class_code->currentText());
        sq += " class_code = '" + pub::getStr(sys_class, "^", pos + 1) + "',";// class_code '系统类别';

        pos = pub::searchStr(fee_code, "^", ui->cbb_fee_code->currentText());
        sq += " fee_code = '" + pub::getStr(fee_code, "^", pos + 1) + "',";//  fee_code '最小费用代码';

        pos = pub::searchStr(drug_type, "^", ui->cbb_drug_type->currentText());
        sq += " drug_type = '" + pub::getStr(drug_type, "^", pos + 1) + "',";//  drug_type '药品类别';

        pos = pub::searchStr(drug_quality, "^", ui->cbb_drug_quality->currentText());
        sq += " drug_quality = '" + pub::getStr(drug_quality, "^", pos + 1) + "',";//  drug_quality '药品性质';

        sq += " specs = '" + ui->le_specs->text().trimmed() + "',";// specs '规格';
        sq += " retail_price = " + ui->le_retail_price->text() + ",";// retail_price '参考零售价';
        sq += " purchase_price = " + ui->le_purchase_price->text() + ",";// purchase_price '最新购入价';
        sq += " pack_unit = '" + ui->cbb_pack_unit->currentText() + "',"; //pack_unit'包装单位';
        sq += " pack_qty = " + ui->le_pack_qty->text() + ",";// pack_qty '包装数';
        sq += " min_unit = '" + ui->cbb_min_unit->currentText() + "',"; // min_unit'最小单位';

        pos = pub::searchStr(dose_models, "^", ui->cbb_dose_model_code->currentText());
        sq += " dose_model_code = '" + pub::getStr(dose_models, "^", pos + 1) + "',";//  dose_model_code '剂型编码';

        sq += " base_dose =" + ui->le_base_dose->text() + ",";// base_dose '基本剂量';
        sq += " dose_unit = '" + ui->cbb_dose_unit->currentText() + "',"; // dose_unit'剂量单位';

        if(ui->ckb_valid_state->isChecked())// + valid_state '有效性标志 1 在用 0 停用 2 废弃';
        {
            sq += " valid_state = '0',";
        }else{
            sq += " valid_state = '1',";//
        }

        if(ui->ckb_self_flag->isChecked())// + self_flag '自制标志 0-非自产，1-自产';
        {
            sq += " self_flag = '1',";
        }else{
            sq += " self_flag = '0',";//
        }

        if(ui->ckb_test_flag->isChecked())// + test_flag '是否需要试敏 0不需要1需要';
        {
            sq += " test_flag = '1',";
        }else{
            sq += " test_flag = '0',";//
        }

        if(ui->ckb_show_flag->isChecked())// + show_flag '大屏幕显示标记 0非屏幕显示  1为大屏幕显示'
        {
            sq += " show_flag = '1',";;
        }else{
            sq += " show_flag = '0',";//
        }

        pos = pub::searchStr(producer_code, "^", ui->cbb_producer_code->currentText());
        sq += " producer_code = '" + pub::getStr(producer_code, "^", pos + 1) + "',";//  producer_code '生产厂家';

        sq += " approve_info = '" + ui->le_approve_info->text().trimmed() + "',";// approve_info '批文信息';
        sq += " manual = '" + ui->pt_manual->toPlainText() + "',";// + manual '说明书内容';
        sq += " oper_code = '" + pub::usr_code + "',";// oper_code '操作员';
        sq += " oper_date = sysdate,";// + oper_date '操作时间';

        if(ui->ckb_is_inject->isChecked())// is_inject '注射剂';
        {
            sq += " is_inject = '1',";
        }else{
            sq += " is_inject = '0',";
        }

        if(ui->ckb_is_antibacterial->isChecked())   //is_antibacterial '抗菌药';
        {
            sq += " is_antibacterial = '1',";
        }else{
            sq += " is_antibacterial = '0',";
        }

        if(ui->ckb_is_03->isChecked())  //is_03 '基药标志';
        {
            sq += " is_03 = '1',";
        }else{
            sq += " is_03 = '0',";
        }
        if(ui->ckb_is_9906->isChecked())  //is_9906 '集采药品标志';
        {
            sq += " is_9906 = '1',";
        }else{
            sq += " is_9906 = '0',";
        }

        if(ui->ckb_split_type->isChecked())  //拆分标志
        {
            sq += " split_type = '0',";
        }else{
            sq += " split_type = '1',";
        }

        sq += " package_num = " + ui->le_package_num->text() + ",";// '整件包装数量';

        pos = pub::searchStr(drug_consume_depts, "^", ui->cbb_dept_code->currentText());
        QString tmp_dept ;
        if(pos == 0)
        {
            tmp_dept = "0";
        }
        else
        {
            tmp_dept = pub::getStr(drug_consume_depts, "^", pos + 1);
        }
        sq += " dept_code = '" + tmp_dept + "',";//dept_code '统计关联科室，药品主要使用科室';

        pos = pub::searchStr(duty_constrains, "^", ui->cbb_duty_constrain->currentText());
        sq += " duty_constrain = '" + pub::getStr(duty_constrains, "^", pos + 1) + "', ";//  duty_constrain '职级限定';

        pos = pub::searchStr(item_grade, "^", ui->cbb_item_grade->currentText());
        sq += "item_grade = '" + pub::getStr(item_grade, "^", pos + 1) + "', ";// 药品等级

        QString id_code = ui->le_id_code->text().trimmed();
        if(id_code.length() == 20)
        {
            id_code = id_code.mid(0, 7);
        }

        sq += " id_code = '" + id_code + "',";// 药品 id 编码;
        sq += " id_code_count = " + ui->le_id_code_count->text() ;// 药品 id 编码容量;

        //sq += "'',";// + phy_function1 '一级药理作用';
        //sq += "'',";// + phy_function2 '二级药理作用';
        //sq += "'',";// + phy_function3 '三级药理作用';

        sq += " where drug_code = '" + ui->le_drug_code->text() + "'";// drug_code'药品编码';
        qDebug()<<"修改药品基础数据："<<sq;
    }
    if(!qro->exec(sq))
    {
        QMessageBox::warning(this, "注意", "保存失败！\n" + qro->lastError().text());
    }
    else
    {
        QMessageBox::warning(this, "注意", "保存成功！" );
        item_info_clear();
    }
}

bool Yk_baseitem::item_check()
{
    //有效性校验
    int test_num;
    double test_double;

    if(ui->le_drug_code->text().isEmpty())  // '药品编码';
    {
        QMessageBox::information(this, "注意", "请先选定或新建一个药品项目！");
        return false;
    }

    if(ui->le_trade_name->text().isEmpty())// '商品名称';
    {
        QMessageBox::information(this, "注意", "药品名称不可以空白！");
        ui->le_trade_name->setFocus();
        return false;
    }

    if(ui->le_spell_code->text().isEmpty())// '商品名拼音码';
    {
        QMessageBox::information(this, "注意", "药品拼音码不可以空白！");
        ui->le_spell_code->setFocus();
        return false;
    }
    if(ui->le_specs->text().isEmpty())// '规格';
    {
        QMessageBox::information(this, "注意", "药品规格不可以空白！");
        ui->le_specs->setFocus();
        return false;
    }

    if(ui->le_base_dose->text().isEmpty())// '基本剂量';
    {
        QMessageBox::information(this, "注意", "药品基本剂量不可以空白！");
        ui->le_base_dose->setFocus();
        return false;
    }
    else
    {
        test_double = ui->le_base_dose->text().toDouble();
        if(test_double < 0 || qFuzzyCompare(test_double, 0))
        {
            QMessageBox::information(this, "注意", "药品基本剂量数值无效！");
            ui->le_base_dose->setFocus();
            return false;
        }
    }

    if(ui->le_pack_qty->text().isEmpty())// '包装数';
    {
        QMessageBox::information(this, "注意", "药品包装数量不可以空白！");
        ui->le_pack_qty->setFocus();
        return false;
    }
    else
    {
        test_num = ui->le_pack_qty->text().toUInt();
        if(test_num < 1)
        {
            QMessageBox::information(this, "注意", "药品包装数量数值无效！");
            ui->le_pack_qty->setFocus();
            return false;
        }
    }

    if(ui->cbb_class_code->currentText().isEmpty()) //  '系统类别';
    {
        QMessageBox::information(this, "注意", "药品系统类别不可以空白！");
        ui->cbb_class_code->setFocus();
        return false;
    }

    if(ui->cbb_fee_code->currentText().isEmpty()) //  '最小费用代码';
    {
        QMessageBox::information(this, "注意", "药品费用类别不可以空白！");
        ui->cbb_fee_code->setFocus();
        return false;
    }

    if(ui->cbb_drug_type->currentText().isEmpty()) //  '药品类别';
    {
        QMessageBox::information(this, "注意", "药品类别不可以空白！");
        ui->cbb_drug_type->setFocus();
        return false;
    }

    if(ui->cbb_dose_unit->currentText().isEmpty()) //  '剂量单位';
    {
        QMessageBox::information(this, "注意", "药品剂量单位不可以空白！");
        ui->cbb_dose_unit->setFocus();
        return false;
    }

    if(ui->cbb_drug_quality->currentText().isEmpty()) //  '药品性质';
    {
        QMessageBox::information(this, "注意", "药品性质不可以空白！");
        ui->cbb_drug_quality->setFocus();
        return false;
    }

    if(ui->cbb_min_unit->currentText().isEmpty()) //  '最小单位';
    {
        QMessageBox::information(this, "注意", "药品最小使用单位不可以空白！");
        ui->cbb_min_unit->setFocus();
        return false;
    }

    if(ui->cbb_producer_code->currentText().isEmpty()) //  '生产厂家';
    {
        QMessageBox::information(this, "注意", "药品生产厂家不可以空白！");
        ui->cbb_producer_code->setFocus();
        return false;
    }
    else
    {
        test_num = pub::searchStr(producer_code, "^", ui->cbb_producer_code->currentText()) ;
        if(test_num == 0)
        {
            QMessageBox::information(this, "注意", "药品生产厂家名称无效！");
            ui->cbb_producer_code->setFocus();
            return false;
        }
    }

    if(ui->cbb_dept_code->currentText().isEmpty()) //  '统计关联科室，药品主要使用科室';
    {
        QMessageBox::information(this, "注意", "药品关联统计科室不可以空白！");
        ui->cbb_dept_code->setFocus();
        return false;
    }

    if(ui->le_retail_price->text().isEmpty())// '参考零售价';
    {
        QMessageBox::information(this, "注意", "药品参考零售价不可以空白！");
        ui->le_retail_price->setFocus();
        return false;
    }
    else
    {
        test_double = ui->le_retail_price->text().toDouble();
        if(test_double <= 0 || qFuzzyCompare(test_double, 0))
        {
            QMessageBox::information(this, "注意", "药品参考零售价数量数值无效！");
            ui->le_retail_price->setFocus();
            return false;
        }
    }

    if(ui->le_purchase_price->text().isEmpty())// '最新购入价';
    {
        QMessageBox::information(this, "注意", "药品最新购入价不可以空白！");
        ui->le_purchase_price->setFocus();
        return false;
    }
    else
    {
        test_double = ui->le_purchase_price->text().toDouble();
        if(test_double < 0 || qFuzzyCompare(test_double, 0))
        {
            QMessageBox::information(this, "注意", "药品最新购入价数量数值无效！");
            ui->le_purchase_price->setFocus();
            return false;
        }
    }

    if(ui->cbb_item_grade->currentText().isEmpty()) //  药品等级
    {
        QMessageBox::information(this, "注意", "药品等级不可以空白！");
        ui->cbb_item_grade->setFocus();
        return false;
    }

    if(ui->cbb_duty_constrain->currentText().isEmpty()) //  职级限定
    {
        QMessageBox::information(this, "注意", "职级限定不可以空白！");
        ui->cbb_duty_constrain->setFocus();
        return false;
    }

    if(ui->le_package_num->text().isEmpty())// '整件包装数量';
    {
        //数量空白，默认置 0
        ui->le_package_num->setText("0");
    }
    else
    {
        test_num = ui->le_package_num->text().toUInt();
        if(ui->le_package_num->text().trimmed() != "0" && test_num < 1)
        {
            //
            QMessageBox::information(this, "注意", "药品整件包装数量数值无效！");
            ui->le_package_num->setFocus();
            return false;
        }
    }

    QString id_code_count = ui->le_id_code_count->text().trimmed();
    if(id_code_count.isEmpty())
    {
        ui->le_id_code_count->setText("0");
        id_code_count = "0";
    }

    test_num = id_code_count.toUInt();
    if(id_code_count != "0" && test_num < 1)
    {
        //
        QMessageBox::information(this, "注意", "药品标志码容量数量数值无效！");
        ui->le_id_code_count->setFocus();
        return false;
    }

    if(ui->cbb_class_code->currentText() == "中草药")
    {
        //草药
        ui->le_id_code->setText("0");
        return true;
    }


    if(ui->le_approve_info->text().isEmpty())// '批文信息';
    {
        QMessageBox::information(this, "注意", "药品批文号不可以空白！");
        ui->le_approve_info->setFocus();
        return false;
    }

    if(ui->cbb_pack_unit->currentText().isEmpty()) // '包装单位';
    {
        QMessageBox::information(this, "注意", "药品包装单位不可以空白！");
        ui->cbb_pack_unit->setFocus();
        return false;
    }
    if(ui->cbb_dose_model_code->currentText().isEmpty()) //  '剂型编码';
    {
        QMessageBox::information(this, "注意", "药品剂型不可以空白！");
        ui->cbb_dose_model_code->setFocus();
        return false;
    }

    QString id_code = ui->le_id_code->text().trimmed();

    if(id_code.isEmpty()) //  编码
    {
        QMessageBox::information(this, "注意", "药品识别码不可以空白！");
        ui->le_id_code->setFocus();
        return false;
    }

    int len = id_code.length();
    if( len != 6 && len != 7 && len != 13 && len != 20 )
    {
        QMessageBox::information(this, "注意", "药品识别码长度无效！");
        ui->le_id_code->setFocus();
        return false;
    }

    if(ui->ckb_self_flag->isChecked())
    {
        if(id_code.length() != 6 )
        {
            QMessageBox::information(this, "注意", "自制药品编码长度应为 6 ！");
            ui->le_id_code->setFocus();
            return false;
        }
    }
    else
    {
        if(id_code.length() == 6 )
        {
            QMessageBox::information(this, "注意", "外购药品编码长度不应为 6 ！");
            ui->le_id_code->setFocus();
            return false;
        }
    }

    //ui->cbb_phy_function1->setCurrentIndex(-1);//  '一级药理作用';
    //ui->cbb_phy_function2->setCurrentIndex(-1);//  '二级药理作用';
    //ui->cbb_phy_function3->setCurrentIndex(-1);//  '三级药理作用';
    //ui->cbb_item_grade->setCurrentIndex(-1);//
    return true;
}
void Yk_baseitem::on_pb_search_cpny_clicked()
{
    //drug_dept_code,
    QString sq;
    sq = "select fac_code 公司编码, fac_name 公司名称, "
         " case when company_type = '0' then '生产厂家' else '经销商' end 类型,"
         " spell_code, valid_flag 在用, company_type "
         " from PHA_COM_COMPANY where 1 = 1 ";

    if(ui->ckb_in_use->isChecked())
    {
        sq += " and valid_flag = '1' ";
    }

    QString company_type = "'company_type'";
    if(ui->ckb_factory->isChecked())
    {
        company_type += ", '0'";
    }

    if(ui->ckb_dealer->isChecked())
    {
        company_type += ", '1'";
    }

    sq += " and company_type in (" + company_type + ") ";

    sq += " and (SPELL_CODE like '%" + ui->le_key_com->text().trimmed().toUpper() ;
    sq += "%' or FAC_NAME like '%" + ui->le_key_com->text().trimmed() + "%' )";

    sq += " order by company_type, fac_name  ";

    qDebug()<<"提取供应关系列表："<<sq;

    md_cpny->setQuery(sq, pub::db_o);

    ui->tvList->setModel(md_cpny);
    int width = ui->tvList->horizontalHeader()->width();
    pub::setColumnWidth(ui->tvList, "0.15^0.5^0.15^0^0.1", width, 10);

}

void Yk_baseitem::on_pb_new_company_clicked()
{
    is_new_fac = true; //新增
    ui->le_company_name->setReadOnly(false);
    ui->le_company_spell->setReadOnly(false);
    ui->rb_dealer->setEnabled(true);
    ui->rb_factory->setEnabled(true);

    ui->le_company_name->clear();
    ui->le_company_spell->clear();

    sq = "select SEQ_PHA_CONSTANT_ID.nextval from dual";
    qro->exec(sq);
    qro->next();

    ui->le_company_code->setText( qro->value(0).toString() );
}

void Yk_baseitem::on_pb_save_cpny_clicked()
{

    if(is_new_fac)
    {
        //新增

        if(ui->le_company_name->text().trimmed().isEmpty())
        {
            QMessageBox::warning(this, "注意", "公司名称不可以为空！");
            return;
        }

        if(!ui->rb_factory->isChecked() && !ui->rb_dealer->isChecked())
        {
            QMessageBox::warning(this, "注意", "生产厂家或经销商必须选择一项！");
            return;
        }

        QString type, valid;
        if(ui->rb_factory->isChecked())
        {
            type = "0";
        }else{
            type = "1";
        }

        if(ui->ckb_valid->isChecked())
        {
            valid = "1";
        }else{
            valid = "0";
        }

        sq = "insert into pha_com_company ("
             "fac_code, fac_name, "
             "spell_code, company_type, "
             "oper_code, oper_date, valid_flag"
             ") values(";
        sq += "'" + ui->le_company_code->text() + "',"; //编码
        sq += "'" + ui->le_company_name->text().trimmed() + "',"; //名称
        sq += "'" + ui->le_spell_code->text().trimmed().toUpper() + "',"; //拼音
        sq += "'" + type + "',"; // company type
        sq += "'" + pub::usr_code + "',"; //
        sq += "sysdate,"; //
        sq += "'" + valid + "'"; //
        sq += ")";
    }
    else
    {
        //修改
        sq = "update pha_com_company set ";

        sq += " valid_flag = " ;
        if(ui->ckb_valid->isChecked())
        {
            sq += "'1'";
        }else{
            sq += "'0'";
        }
        sq += " where fac_code = '" + ui->le_company_code->text() + "'";
    }

    qDebug()<<"供应关系变更："<<sq;
    if(!qro->exec(sq))
    {
        QMessageBox::warning(this, "注意", "Sql语句错误！\n" + sq);
        return;
    }

    QMessageBox::information(this, "注意", "保存完成！" );
    ui->le_spell_code->clear();
    ui->le_company_code->clear();
    ui->le_company_name->clear();
}

void Yk_baseitem::generate_specs()
{
    QString base, pack, unit ;
    base = ui->le_base_dose->text() + ui->cbb_dose_unit->currentText();
    pack = ui->le_pack_qty->text() + ui->cbb_min_unit->currentText();
    unit = ui->cbb_pack_unit->currentText();
    if(base.isEmpty() || pack.isEmpty() || unit.isEmpty())
    {
        return;
    }
    ui->le_specs->setText(base + "*" + pack + "/" + unit);
}

void Yk_baseitem::on_le_base_dose_textChanged(const QString &arg1)
{
    if(is_new_drug)
    {
        generate_specs();
    }
}

void Yk_baseitem::on_cbb_dose_unit_currentTextChanged(const QString &arg1)
{
    if(is_new_drug)
    {
        generate_specs();
    }
}

void Yk_baseitem::on_cbb_min_unit_currentTextChanged(const QString &arg1)
{
    if(is_new_drug)
    {
        generate_specs();
    }
}

void Yk_baseitem::on_le_pack_qty_textChanged(const QString &arg1)
{
    if(is_new_drug)
    {
        generate_specs();
    }
}

void Yk_baseitem::on_cbb_pack_unit_currentTextChanged(const QString &arg1)
{
    if(is_new_drug)
    {
        generate_specs();
    }
}

void Yk_baseitem::on_le_trade_name_textChanged(const QString &arg1)
{
    if(is_new_drug)
    {
        ui->le_spell_code->setText(pub::pub::getFirstLetters(arg1));
    }
}

void Yk_baseitem::on_le_id_code_returnPressed()
{
    QString id_code = ui->le_id_code->text().trimmed();

    if(id_code.length() == 20)
    {
        id_code = id_code.mid(0, 7);
        ui->le_id_code->setText(id_code);
    }
}
void Yk_baseitem::on_le_company_name_textChanged(const QString &arg1)
{
    if(is_new_fac)
    {
        ui->le_company_spell->setText(pub::pub::getFirstLetters(arg1));
    }
}

